package logic

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"

	"github.com/iriver/ai-offer/backend/internal/middleware"
	"github.com/iriver/ai-offer/backend/internal/model"
	"github.com/iriver/ai-offer/backend/internal/svc"
	"github.com/iriver/ai-offer/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type GetCurrentUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *middleware.Claims
}

func NewGetCurrentUserLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *middleware.Claims) *GetCurrentUserLogic {
	return &GetCurrentUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *GetCurrentUserLogic) GetCurrentUser() (resp *types.UserResponse, err error) {
	// 从数据库中获取完整的用户信息
	user, err := l.svcCtx.UserStore.FindOne(l.r.UserId)
	if err != nil {
		if err == model.ErrNotFound {
			l.Logger.Infof("用户不存在: %d", l.r.UserId)
			return nil, httpx.NewCodeError(types.ErrUserNotFound, "用户不存在")
		}
		l.Logger.Errorf("查询用户失败: %v", err)
		return nil, httpx.NewCodeError(types.ErrDatabase, "获取用户信息失败，请稍后重试")
	}

	// 返回用户信息
	resp = &types.UserResponse{
		Id:        user.ID,
		Email:     user.Email,
		Name:      user.Name,
		AvatarUrl: user.AvatarUrl,
		Role:      user.Role,
		CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt: user.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	return resp, nil
}

// 从请求中获取用户
func GetUserFromRequest(r *http.Request) (*middleware.Claims, error) {
	userInfoStr := r.Header.Get("X-User-Info")
	if userInfoStr == "" {
		return nil, errors.New("未找到用户信息")
	}

	var claims middleware.Claims
	if err := json.Unmarshal([]byte(userInfoStr), &claims); err != nil {
		return nil, err
	}

	return &claims, nil
}
